using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SmartLink.Infrastructure;

namespace SmartLink.JobForm
{
    public partial class JobForm : Form
    {
        public static string sApplicationPath = System.Environment.CurrentDirectory;
        private string serviceName = "SmartLink.Job";
        public JobForm()
        {
            InitializeComponent();
            if (ServiceControllerHelper.IsExistWindowsServer(serviceName))
            {
                btnInstall.Enabled = false;
                tbMsg.AppendText("服务已经安装\r\n");
            }
            if (ServiceControllerHelper.IsRuningWindowsServer(serviceName))
            {
                btnStart.Enabled = false;
                tbMsg.AppendText("服务已经启动");
            }
        }

        private void btnInstall_Click(object sender, EventArgs e)
        {
            btnInstall.Enabled = false;
            tbMsg.Text = "开始安装...";
            var command = SetCommand("install");
            var outPut = CmdHelper.Run(command);
            tbMsg.AppendText(outPut);
            btnInstall.Enabled = true;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            tbMsg.Text = "服务启动中...";
            var command = SetCommand("start");
            var outPut = CmdHelper.Run(command);
            tbMsg.AppendText(outPut);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            tbMsg.Text = "服务停止中...";
            var command = SetCommand("stop");
            var outPut = CmdHelper.Run(command);
            tbMsg.AppendText(outPut);
            btnStart.Enabled = true;
        }

        private void btnUninstall_Click(object sender, EventArgs e)
        {
            btnUninstall.Enabled = false;
            tbMsg.Text = "准备卸载...";
            var command = SetCommand("uninstall");
            var outPut = CmdHelper.Run(command);
            tbMsg.AppendText(outPut);
            btnUninstall.Enabled = true;
            btnInstall.Enabled = true;
        }

        private string SetCommand(string command)
        {
            var sbCommand = new StringBuilder();
            sbCommand.Append("cd\\&");
            sbCommand.Append(sApplicationPath);
            sbCommand.Append("\\");
            sbCommand.Append(serviceName);
            sbCommand.Append(".exe ");
            sbCommand.Append(command);
            return sbCommand.ToString();
        }
    }
}
